package com.santu.edu.supporter.biz.common.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.santu.edu.supporter.biz.common.pojo.dto.WxLoginResponse;
import com.santu.edu.supporter.biz.common.service.WxAppReqService;
import com.santu.edu.supporter.exception.BizException;
import com.santu.edu.supporter.exception.CustomError;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author luoyaoqi
 * @createTime 2024/2/23
 * @description
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WxAppReqServiceImpl implements WxAppReqService {

    public static String WX_APP_LOGIN = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    private final OkHttpClient okHttpClient;

    @Value("${wx.appId}")
    private String appId;

    @Value("${wx.appSecret}")
    private String appSecret;

    @Override
    public WxLoginResponse wxLogin(String code) {
        Request request = new Request.Builder()
                .url(String.format(WX_APP_LOGIN, appId, appSecret, code))
                .get()
                .build();
        WxLoginResponse response = doExecute(request, WxLoginResponse.class);
        if (StrUtil.isBlank(response.getOpenid())) {
            throw BizException.causeBy(CustomError.createCustomError(response.getErrcode(),response.getErrmsg()));
        }
        return response;
    }


    private <T> T doExecute(Request request, Class<T> aclass) {
        for (int i = 0; i < 3; i++) {
            try (final Response response = okHttpClient.newCall(request).execute();
                 ResponseBody body = response.body()) {
                if (response.isSuccessful()) {
                    if (body == null) {
                        continue;
                    }
                    final String bodyContent = body.string();
                    if (StrUtil.isBlank(bodyContent)) {
                        continue;
                    }
                    return JSON.parseObject(bodyContent, aclass);
                }
            } catch (Exception e) {
                log.error("请求异常{}", e.getLocalizedMessage());
            }
        }
        throw BizException.causeBy(CustomError.REQUEST_ERROR);
    }


}
